<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="pd.showSearch">
        <el-card shadow="hover">
          <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            <el-form-item label="树节点名" prop="treeName">
              <el-input v-model="pd.queryParams.treeName" placeholder="请输入树节点名" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['demo:tree:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        v-loading="pd.loading" :data="pd.treeList" row-key="id" :default-expand-all="pd.isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}" ref="treeTableRef">
        <el-table-column label="父id" align="center" prop="parentId" />
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="部门id" align="center" prop="deptId" />
        <el-table-column label="用户id" align="center" prop="userId" />
        <el-table-column label="树节点名" align="center" prop="treeName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['demo:tree:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['demo:tree:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['demo:tree:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改测试树对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
      <el-form ref="treeFormRef" :model="pd.form" :rules="rules" label-width="80px">
        <el-form-item label="父id" prop="parentId">
          <el-tree-select
            v-model="pd.form.parentId" :data="pd.treeOptions"
            :props="{ value: 'id', label: 'treeName', children: 'children' }"
            value-key="id" placeholder="请选择父id" check-strictly />
        </el-form-item>
        <el-form-item label="部门id" prop="deptId">
          <el-input v-model="pd.form.deptId" placeholder="请输入部门id" />
        </el-form-item>
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="pd.form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="值" prop="treeName">
          <el-input v-model="pd.form.treeName" placeholder="请输入值" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tree" lang="ts">
import { TreeVO, listTree, getTree, delTree, addTree, updateTree } from "@/views/demo/tree/api";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const queryFormRef = ref<ElFormInstance>();
const treeFormRef = ref<ElFormInstance>();
const treeTableRef = ref<ElTableInstance>()

const pd = reactive({
  treeList: <TreeVO[]>([]),
  treeOptions: <TreeVO[]>([]),
  buttonLoading: false,
  showSearch: true,
  isExpandAll: true,
  loading: false,
  form: <TreeVO>{},
  queryParams: <TreeVO>{
    parentId: undefined,
    deptId: undefined,
    userId: undefined,
    treeName: undefined,
  },
  rules: <ElFormRules>{
    id: [      { required: true, message: "主键不能为空", trigger: "blur" }    ],
    parentId: [      { required: true, message: "父id不能为空", trigger: "blur" }    ],
    deptId: [      { required: true, message: "部门id不能为空", trigger: "blur" }    ],
    userId: [      { required: true, message: "用户id不能为空", trigger: "blur" }    ],
    treeName: [      { required: true, message: "值不能为空", trigger: "blur" }    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

/** 查询测试树列表 */
async function getList() {
  pd.loading = true;
  const res = await listTree(pd.queryParams);
  const data = proxy?.handleTree<TreeVO>(res.data, "id", "parentId");
  if (data) {
    pd.treeList = data;
    pd.loading = false;
  }
}

/** 查询测试树下拉树结构 */
async function getTreeSelect() {
  pd.treeOptions = [];
  const data: TreeVO = { id: 0, treeName: '顶级节点', children: [] };
  data.children = pd.treeList;
  pd.treeOptions.push(data);
}

// 取消按钮
function cancel() {
  reset();
  pd.dialog.visible = false;
}

// 表单重置
function reset() {
  pd.form = {}
  treeFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row?: TreeVO) {
  reset();
  getTreeSelect();
  if (row && row.id) {
    pd.form.parentId = row.id;
  } else {
    pd.form.parentId = 0;
  }
  pd.dialog.visible = true;
  pd.dialog.title = "添加测试树";
}

/** 展开/折叠操作 */
function handleToggleExpandAll() {
  pd.isExpandAll = !pd.isExpandAll;
  toggleExpandAll(pd.treeList, pd.isExpandAll)
}

/** 展开/折叠操作 */
function toggleExpandAll(data: TreeVO[], status: boolean) {
  data.forEach((item) => {
    treeTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
async function handleUpdate(row: TreeVO) {
  reset();
  await getTreeSelect();
  if (row) {
    pd.form.parentId = row.id;
  }
  const res = await getTree(row.id);
  Object.assign(pd.form, res.data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改测试树";
}

/** 提交按钮 */
function submitForm() {
  treeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateTree(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addTree(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row: TreeVO) {
  await proxy?.$modal.confirm('是否确认删除测试树编号为"' + row.id + '"的数据项？');
  pd.loading = true;
  await delTree(row.id).finally(() => pd.loading = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

onMounted(() => {
  getList();
});
</script>
